#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
页签卡片UI演示 - 简化版
展示新的页签卡片界面设计
"""

import sys
import os
from PyQt5.QtWidgets import (
    QApplication, QMainWindow, QVBoxLayout, QPushButton,
    QLabel, QComboBox, QWidget, QTextEdit, QSpinBox, QHBoxLayout,
    QGroupBox, QTabWidget
)
from PyQt5.QtCore import pyqtSignal, QObject
from datetime import datetime

# 配置信息
name_path = {
    "dlt": {"name": "大乐透", "path": "./scripts/dlt/"},
    "ssq": {"name": "双色球", "path": "./scripts/ssq/"},
    "plw": {"name": "排列5", "path": "./scripts/plw/"}
}

class TabbedUI(QMainWindow):
    """页签卡片式UI演示"""
    
    def __init__(self):
        super().__init__()
        self.initUI()
    
    def initUI(self):
        self.setWindowTitle("🎯 彩票预测 - 页签卡片UI演示")
        self.setGeometry(100, 100, 1000, 700)
        
        main_layout = QVBoxLayout()
        
        # 创建页签容器
        self.tab_widget = QTabWidget()
        
        # 为每个彩票类型创建页签
        for lottery_key, lottery_info in name_path.items():
            tab = self.create_lottery_tab(lottery_key, lottery_info)
            self.tab_widget.addTab(tab, f"🎲 {lottery_info['name']}")
        
        main_layout.addWidget(self.tab_widget)
        
        # 全局日志
        self.log_box = QTextEdit()
        self.log_box.setReadOnly(True)
        self.log_box.setMaximumHeight(150)
        self.log_box.setPlainText("页签卡片UI演示启动成功！\\n请选择页签体验新界面...")
        main_layout.addWidget(QLabel("📜 系统日志"))
        main_layout.addWidget(self.log_box)
        
        central_widget = QWidget()
        central_widget.setLayout(main_layout)
        self.setCentralWidget(central_widget)
    
    def create_lottery_tab(self, lottery_key, lottery_info):
        """创建彩票页签"""
        tab = QWidget()
        layout = QVBoxLayout()
        
        # 信息卡片
        info_group = QGroupBox(f"🎯 {lottery_info['name']} 信息")
        info_layout = QVBoxLayout()
        
        rules = self.get_rules(lottery_key)
        info_layout.addWidget(QLabel(rules))
        info_group.setLayout(info_layout)
        layout.addWidget(info_group)
        
        # 算法卡片
        algo_group = QGroupBox(f"🤖 可用算法")
        algo_layout = QVBoxLayout()
        
        # 算法选择
        algo_select = QHBoxLayout()
        algo_select.addWidget(QLabel("算法:"))
        combo = QComboBox()
        combo.addItems(self.get_algorithms(lottery_key))
        algo_select.addWidget(combo)
        algo_layout.addLayout(algo_select)
        
        # 预测按钮
        predict_btn = QPushButton("🎯 开始预测")
        predict_btn.clicked.connect(lambda: self.demo_predict(lottery_key))
        algo_layout.addWidget(predict_btn)
        
        algo_group.setLayout(algo_layout)
        layout.addWidget(algo_group)
        
        # 训练卡片
        train_group = QGroupBox(f"🎓 模型训练")
        train_layout = QVBoxLayout()
        
        # 模型状态
        status_label = QLabel("模型状态：演示模式")
        train_layout.addWidget(status_label)
        
        # 训练按钮
        train_buttons = QHBoxLayout()
        lstm_btn = QPushButton("🤖 训练LSTM-CRF")
        lstm_btn.clicked.connect(lambda: self.demo_train(lottery_key, "LSTM-CRF"))
        train_buttons.addWidget(lstm_btn)
        
        if lottery_key == "plw":
            seq_btn = QPushButton("🔥 训练序列LSTM")
            seq_btn.clicked.connect(lambda: self.demo_train(lottery_key, "序列LSTM"))
            train_buttons.addWidget(seq_btn)
        
        train_layout.addLayout(train_buttons)
        train_group.setLayout(train_layout)
        layout.addWidget(train_group)
        
        # 结果显示
        result_group = QGroupBox("🏆 预测结果")
        result_layout = QVBoxLayout()
        result_text = QTextEdit()
        result_text.setReadOnly(True)
        result_text.setMaximumHeight(200)
        result_text.setObjectName(f"result_{lottery_key}")
        result_text.setPlainText(f"{lottery_info['name']}预测结果将在此显示...")
        result_layout.addWidget(result_text)
        result_group.setLayout(result_layout)
        layout.addWidget(result_group)
        
        tab.setLayout(layout)
        return tab
    
    def get_rules(self, lottery_key):
        """获取彩票规则"""
        rules = {
            "dlt": "🔴 前区：5个号码(01-35) | 🔵 后区：2个号码(01-12)",
            "ssq": "🔴 红球：6个号码(01-33) | 🔵 蓝球：1个号码(01-16)", 
            "plw": "📟 数字：5个位置(万千百十个位，0-9，允许重复)"
        }
        return rules.get(lottery_key, "未知规则")
    
    def get_algorithms(self, lottery_key):
        """获取算法列表"""
        base_algos = ["🤖 LSTM-CRF", "🚀 梯度提升", " 模式记忆", "⚖️ 权重专家"]
        if lottery_key == "plw":
            base_algos.insert(1, "🔥 序列LSTM(专用)")
        else:
            base_algos.insert(1, "🔥 序列LSTM(确定性)")
        return base_algos
    
    def demo_predict(self, lottery_key):
        """演示预测功能"""
        result_display = self.findChild(QTextEdit, f"result_{lottery_key}")
        if result_display:
            import random
            lottery_name = name_path[lottery_key]['name']
            
            if lottery_key == "dlt":
                red = sorted(random.sample(range(1, 36), 5))
                blue = sorted(random.sample(range(1, 13), 2))
                result = f"前区：{red}\\n后区：{blue}"
            elif lottery_key == "ssq":
                red = sorted(random.sample(range(1, 34), 6))
                blue = [random.randint(1, 16)]
                result = f"红球：{red}\\n蓝球：{blue}"
            else:  # plw
                numbers = [random.randint(0, 9) for _ in range(5)]
                result = f"数字：{numbers}"
            
            text = f"🎯 {lottery_name} 预测结果\\n"
            text += f"时间：{datetime.now().strftime('%H:%M:%S')}\\n"
            text += "=" * 30 + "\\n"
            text += f"{result}\\n"
            text += f"置信度：{random.uniform(0.7, 0.9):.3f}"
            
            result_display.setPlainText(text)
        
        self.log_box.append(f"✅ {name_path[lottery_key]['name']} 预测完成")
    
    def demo_train(self, lottery_key, model_type):
        """演示训练功能"""
        lottery_name = name_path[lottery_key]['name']
        self.log_box.append(f"🎓 开始训练 {lottery_name} {model_type} 模型...")
        self.log_box.append(f"✅ {lottery_name} {model_type} 训练完成（演示）")

def main():
    app = QApplication(sys.argv)
    window = TabbedUI()
    window.show()
    
    print("🎯 页签卡片UI演示启动成功！")
    print("📑 每个彩票类型都有独立页签")
    print(" 显示各自的可用算法")
    print("🎓 提供专门的训练按钮")
    
    sys.exit(app.exec_())

if __name__ == "__main__":
    main()